package com.brotherly.mpgp.remoteinterface;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.brotherly.framework.app.BaseApplication;
import com.brotherly.framework.event.EventService;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.framework.storage.SimpleStorage;
import com.brotherly.framework.storage.SimpleStorageService;

public class RemoteServerWatcher
{
    public static abstract class RemoteServerTask
    {
        public void error(int errno, String action)
        {
            EventService eventService = (EventService)
                    ServiceManager.getInstance().getService(ServiceManager.EVENT_SERVICE);
            Object[] param1 = new Object[2];
            param1[0] = errno;
            param1[1] = action;
            eventService.signEvent(
                    RemoteServerService.RemoteServer_Event_RemoteServer_Error,
                    param1, getErrorInfo(errno));
        }

        public abstract void execute(String remoteServerRoot, RemoteServer server);
    }

    public static final int FailedThirds = 3;

    protected static RemoteServerWatcher pthis;

    public final static String RemoteServerIP = "202.102.39.26";
    public final static String RemoteServerRoot = "http://" + RemoteServerIP + ":80/strategy/api/";

    public static final int UnknownServer = 1;

    public static String getErrorInfo(int errno)
    {
        if (errno == UnknownServer)
        {
            return "无法连接服务器，请稍后重试。";
        }
        else if (errno == 400)
        {
            return "网络请求格式错误。";
        } else if (errno == 401)
        {
            return "请先登录。";
        } else if (errno == 403)
        {
            return "修改失败。";
        } else if (errno == 404)
        {
            return "未找到此用户。";
        } else if (errno == 409)
        {
            return "用户名已经被使用。";
        }

        return "网络错误，请稍后重试。";
    }

    public static RemoteServerWatcher getInstance()
    {
        if (pthis == null)
            pthis = new RemoteServerWatcher();

        return pthis;
    }

    private String remoteServerRoot = null;

    private ThreadPoolExecutor threadPool;

    public RemoteServerWatcher()
    {

        ArrayBlockingQueue<Runnable> deques = new ArrayBlockingQueue<Runnable>(300);

        threadPool = new ThreadPoolExecutor(0, 1, 1000, TimeUnit.MILLISECONDS, deques,
                new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    public boolean canStart()
    {
        if (ServiceManager.getInstance().getService(ServiceManager.HTTP_SERVICE) != null
                && ServiceManager.getInstance().getService(ServiceManager.SIMPLESTORAGE_SERVICE) != null
                && ServiceManager.getInstance().getService(ServiceManager.LOG_SERVICE) != null)
        {
            return true;
        }

        return false;
    }

    public void executeTask(final RemoteServerTask task)
    {
        threadPool.execute(new Runnable()
        {
            public void run()
            {
                if (remoteServerRoot == null)
                    requestRemoteServerRoot();

                try
                {
                    task.execute(remoteServerRoot, new RemoteServer());
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    public String getGuideRoot()
    {
        String rootUrl = null;

        try
        {
            SimpleStorage storage = ((SimpleStorageService) ServiceManager.getInstance().getService(
                    ServiceManager.SIMPLESTORAGE_SERVICE)).openStorage(RemoteServerService.STORAGE);

            String url = storage.get(RemoteServerService.OPTION_GUIDE);

            if (BaseApplication.isDebugServer)
            {
                String debug_url = storage.get("guide_debug");
                if (debug_url != null)
                    url = debug_url;
            }

            rootUrl = url;
            storage.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return rootUrl;
    }

    protected ThreadPoolExecutor getThreadPool()
    {
        return threadPool;
    }

    public boolean requestRemoteServerRoot()
    {
        // SessionServer server = new SessionServer();
        //
        // JSONObject infos = server.requestGuideInfo(getGuideRoot());
        // if (infos == null)
        // return false;
        //
        // sessionRoot = MapHelper.getString(infos, "session");
        // if (sessionRoot == null)
        // return false;
        remoteServerRoot = RemoteServerRoot;
        return true;
    }

    public void start()
    {
        threadPool.execute(new Runnable()
        {
            public void run()
            {
                requestRemoteServerRoot();
            }
        });
    }

    public void stop()
    {}
}
